import 'dart:io';
import 'package:dio/dio.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:oi_ai_tool/util/http/app_exception.dart';
import 'package:oi_ai_tool/widgets/toast.dart';

// 异常

class MyDioSocketException extends SocketException {
  @override
  late String message;

  MyDioSocketException(
    message, {
    osError,
    address,
    port,
  }) : super(
          message,
          osError: osError,
          address: address,
          port: port,
        );
}

/// 错误处理拦截器
class ErrorInterceptor extends Interceptor {
  // 是否有网
  Future<bool> isConnected() async {
    var connectivityResult = await (Connectivity().checkConnectivity());
    return connectivityResult != ConnectivityResult.none;
  }

  @override
  Future<void> onError(DioException err, ErrorInterceptorHandler errCb) async {
    //TODO 网络异常处理
    // error 统一处理
    EasyLoading.dismiss();
    var appException = AppException.create(err);
    var showError = err.requestOptions.extra['showError'];
    if (showError) {
      OiToast.msg(appException.message);
    }
    var appError = err.copyWith(error: appException);
    return super.onError(appError, errCb);
  }
}
